package controllers

import (
	"encoding/json"
	"strings"
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// FavoriteController 收藏控制器
type FavoriteController struct {
	web.Controller
}

// AddFavorite 添加收藏
func (c *FavoriteController) AddFavorite() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析参数
	var params struct {
		StoreId int64 `json:"store_id"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &params); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证参数
	if params.StoreId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "缺少门店ID参数",
		}
		c.ServeJSON()
		return
	}

	// 检查门店是否存在
	store, err := models.GetStoreById(params.StoreId)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 添加收藏
	id, err := models.AddFavorite(member.Id, params.StoreId)
	if err != nil {
		logs.Error("添加收藏失败: ", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "添加收藏失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "收藏成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// CancelFavorite 取消收藏
func (c *FavoriteController) CancelFavorite() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析参数
	var params struct {
		StoreId int64 `json:"store_id"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &params); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证参数
	if params.StoreId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "缺少门店ID参数",
		}
		c.ServeJSON()
		return
	}

	// 取消收藏
	err = models.CancelFavorite(member.Id, params.StoreId)
	if err != nil {
		logs.Error("取消收藏失败: ", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "取消收藏失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "取消收藏成功",
	}
	c.ServeJSON()
}

// GetFavoriteList 获取收藏列表
func (c *FavoriteController) GetFavoriteList() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 获取收藏列表
	favorites, total, err := models.GetUserFavorites(member.Id, page, pageSize)
	if err != nil {
		logs.Error("获取收藏列表失败: ", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取收藏列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}
	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")
	// 构建响应数据
	var storeList []map[string]interface{}
	for _, favorite := range favorites {
		// 获取门店信息
		store, err := models.GetStoreById(favorite.StoreId)
		if err != nil || store == nil {
			// 跳过不存在的门店
			continue
		}
		imageUrl := store.Images
		if len(imageUrl) > 0 && imageUrl[0] == '/' {
			imageUrl = baseURL + strings.ReplaceAll(imageUrl, "\\", "/")
		}
		storeData := map[string]interface{}{
			"id":             store.Id,
			"name":           store.Name,
			"image":          imageUrl,
			"address":        store.Address,
			"phone":          store.Phone,
			"business_hours": store.BusinessHours,
			"status":         store.Status,
			"favorite_id":    favorite.Id,
			"favorite_at":    favorite.UpdatedAt,
		}

		storeList = append(storeList, storeData)
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取收藏列表成功",
		"data": map[string]interface{}{
			"list":  storeList,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// CheckIsFavorite 检查是否已收藏
func (c *FavoriteController) CheckIsFavorite() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取门店ID参数
	storeId, _ := c.GetInt64("store_id", 0)
	if storeId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "缺少门店ID参数",
		}
		c.ServeJSON()
		return
	}

	// 检查是否已收藏
	isFavorite, err := models.IsFavorite(member.Id, storeId)
	if err != nil {
		logs.Error("检查收藏状态失败: ", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "检查收藏状态失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "检查收藏状态成功",
		"data": map[string]interface{}{
			"is_favorite": isFavorite,
		},
	}
	c.ServeJSON()
}
